package com.csthink.web.infrastructure.security;

import com.csthink.web.infrastructure.security.authentication.parser.AuthenticationParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * The tool for Spring Security authentication and authorization
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-12
 */
@Slf4j
public class AuthenticationHelper {

    /**
     * This is fully ignored by Spring Security , both Authentication and Authorization.
     */
    public static final String[] FULLY_IGNORE_URL_LIST = {
            "/swagger-ui/**", // swagger 3.0.0
            "/swagger-resources/**",
            "/v3/api-docs",
            "/api-docs",
            "/health/**",
            "/images/**",
            "/webjars/**",
            "/actuator/**",
            "/version.txt",
            "/error",
            "/v1/passport/login",
            "/v1/passport/register"
    };

    private AuthenticationParser defaultAuthenticationParser;

    public static boolean matches(HttpServletRequest request, List<AntPathRequestMatcher> matchers) {
        Optional<AntPathRequestMatcher> first = matchers.stream().filter(m -> m.matches(request)).findFirst();
        return first.isPresent();
    }

    public AuthenticationParser getParser(HttpServletRequest request) {
        AuthenticationParser retVal = defaultAuthenticationParser;
//        if (otherAuthenticationParser.match(request)) {
//            retVal = otherAuthenticationParser;
//        }

        if (log.isDebugEnabled()) {
            log.debug("Request {} matched parser {}.", request.getRequestURI(), retVal);
        }
        return retVal;
    }

    @Autowired
    public void setDefaultAuthenticationParser(AuthenticationParser defaultAuthenticationParser) {
        this.defaultAuthenticationParser = defaultAuthenticationParser;
    }

}
